﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Sustainalytics.SharedEntities.CorporateGovernanceResearch;
using Sustainalytics.Synchronization.Interface;

namespace Sustainalytics.Governance.Synchronization
{
    public class CorporateGovernanceAssessmentThresholdsQuery
    {
        private readonly ILogger _logger;
        private readonly Entities.BackOfficeAppSettings _backOfficeAppSettings;
        private readonly CorporateGovernanceDataProvider.CorporateGovernanceDataProvider _corporateGovernanceDataProvider;

        public CorporateGovernanceAssessmentThresholdsQuery(ILogger logger,
            CorporateGovernanceDataProvider.CorporateGovernanceDataProvider corporateGovernanceDataProvider,
            Entities.BackOfficeAppSettings backOfficeAppSettings)
        {
            _logger = logger;
            _corporateGovernanceDataProvider = corporateGovernanceDataProvider;

            _backOfficeAppSettings = backOfficeAppSettings;

            logger.Log($"\nWorking with HBase Thrift server {backOfficeAppSettings.ThriftServer} and Phoenix server {backOfficeAppSettings.PhoenixServer}");
        }

        public IList<GovernanceAssessmentThreshold> Get()
        {
            var callerMethod = new StackFrame(1).GetMethod().Name;

            var sw = Stopwatch.StartNew();

            _logger.Log($"Start getting data from the cluster for {callerMethod}");

            var governanceAssessmentThresholds = Retry.Do(() => _corporateGovernanceDataProvider.GetGovernanceAssessmentThresholds().ToList(),
                      _backOfficeAppSettings.WaitRetryDuration,
                      _logger,
                      _backOfficeAppSettings.RetryNumberOfTimes);

            sw.Stop();

            _logger.Log($"Finished getting data from the cluster for {callerMethod}: " +
                       $"received {governanceAssessmentThresholds.Count} entities" +
                       $" ( duration {sw.Elapsed} )");

            return governanceAssessmentThresholds.ToList();
        }
    }
}
